<template>
  <div class="bg-white shadow-md p-4">
    <Navigation :homeRoute="homeRoute" :currentPage="currentPage" />
  </div>
  <div class="template-management">
    <!-- 添加按钮容器 -->
    <div class="button-container">
      <el-button 
        type="primary" 
        size="large" 
        @click="openAddDialog()"
      >
        新增模板
      </el-button>
    </div>

    <!-- 模板表格容器 -->
    <div class="table-container">
      <el-table 
        :data="templates" 
        class="custom-table"
        :row-height="60"
        style="font-size: 16px;"
      >
        <el-table-column prop="template_id" label="模板ID" width="180" />
        <el-table-column prop="template_name" label="模板名称" width="240" />
        <el-table-column prop="creator_id" label="创建者ID" width="180" />
        <el-table-column prop="content" label="模板内容" width="480">
          <template #default="{ row }">
            <span style="white-space: pre-wrap; line-height: 1.8; font-size: 15px;">{{ row.content }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="240">
          <template #default="{ row }">
            <span style="font-size: 15px;">{{ formatDate(row.create_time) }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="240">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              size="large"
              @click="openEditDialog(row)"
              style="font-size: 15px;"
            >
              编辑
            </el-button>
            <el-button
              link
              type="danger"
              size="large"
              @click="handleDelete(row.template_id)"
              style="font-size: 15px; margin-left: 20px;"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 编辑/添加对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑模板' : '新增模板'"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-loading v-show="loading" element-loading-text="加载中..." />
      
      <el-form 
        :model="form" 
        label-width="120px" 
        ref="formRef"
        :rules="formRules"
        size="large"
        style="font-size: 16px;"
      >
        <template v-if="isEditMode">
          <el-form-item label="模板ID" prop="template_id">
            <el-input
              v-model.number="form.template_id"
              disabled
              placeholder="不可编辑"
              style="font-size: 15px; height: 48px;"
            />
          </el-form-item>
        </template>

        <el-form-item label="模板名称" prop="template_name">
          <el-input
            v-model.trim="form.template_name"
            placeholder="请输入模板名称"
            style="font-size: 15px; height: 48px;"
          />
        </el-form-item>
        
        <el-form-item label="创建者ID" prop="creator_id">
          <el-input
            v-model.number="form.creator_id"
            placeholder="请输入创建者ID"
            style="font-size: 15px; height: 48px;"
          />
        </el-form-item>
        
        <el-form-item label="模板内容" prop="content">
          <el-input
            v-model.trim="form.content"
            placeholder="请输入模板内容"
            type="textarea"
            :rows="6"
            style="font-size: 15px;"
          />
        </el-form-item>

        <el-form-item label="创建时间" prop="create_time">
          <el-input
            v-model="form.create_timeStr"
            placeholder="请输入时间（格式：yyyy-MM-dd HH:mm:ss）"
            @blur="handleTimeInput"
            style="font-size: 15px; height: 48px; width: 320px;"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button 
            @click="closeDialog()" 
            size="large" 
            style="font-size: 15px; padding: 0 24px;"
          >
            取消
          </el-button>
          <el-button 
            type="primary" 
            @click="handleSubmit()" 
            size="large" 
            style="font-size: 15px; padding: 0 24px;"
          >
            {{ isEditMode ? '保存修改' : '新增模板' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { FormInstance } from 'element-plus';
import axios from "axios";
import { ref, reactive, onMounted } from "vue";
import Navigation from '@/components/Navigation.vue';
// 状态管理（新增时间字符串变量）
const currentPage = '病例模板';
const templates = ref<any[]>([]);
const loading = ref(false);
const dialogVisible = ref(false);
const isEditMode = ref(false);
const form = reactive<{
  template_id?: number;
  template_name: string;
  creator_id: number;
  content: string;
  create_time: number; // 存储时间戳
  create_timeStr: string; // 存储输入的时间字符串
}> ({
  template_name: "",
  creator_id: 0,
  content: "",
  create_time: Date.now(),
  create_timeStr: new Date().toISOString().split('T')[0] + ' 00:00:00' // 默认日期
});
const formRef = ref<FormInstance>();

// 表单验证规则
const formRules = reactive({
  template_name: [{ required: true, message: "请输入模板名称", trigger: "blur" }],
  creator_id: [{ required: true, message: "请输入创建者ID", trigger: "blur" }],
  content: [{ required: true, message: "请输入模板内容", trigger: "blur" }],
  create_time: [{ required: true, message: "请输入有效时间", trigger: "blur" }]
});

// 日期格式化函数
const formatDate = (timestamp: number) => {
  return new Date(timestamp).toLocaleString('zh-CN', {
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit'
  });
};

// 时间输入处理函数
const handleTimeInput = (e: any) => {
  const inputValue = e.target.value.trim();
  const date = new Date(inputValue.replace(/-/g, '/')); // 兼容日期格式
  if (isNaN(date.getTime())) {
    form.create_time = Date.now();
    form.create_timeStr = formatDate(form.create_time);
    return alert('时间格式不正确，请使用 yyyy-MM-dd HH:mm:ss 格式');
  }
  form.create_time = date.getTime();
  form.create_timeStr = formatDate(form.create_time);
};

// 加载数据
const fetchData = async () => {
  loading.value = true;
  try {
    const response = await axios.get("/template/findAll");
    templates.value = response.data.map(item => ({
      ...item,
      create_time: item.create_time || Date.now() // 处理可能的null值
    }));
  } catch (err) {
    console.error("数据加载失败:", err);
    alert('数据加载失败，请检查网络或联系管理员');
  } finally {
    loading.value = false;
  }
};

// 打开添加对话框（重置时间为当前日期）
const openAddDialog = () => {
  resetForm();
  form.create_time = Date.now();
  form.create_timeStr = formatDate(form.create_time);
  isEditMode.value = false;
  dialogVisible.value = true;
};

// 打开编辑对话框（转换时间戳为字符串）
const openEditDialog = (row: any) => {
  resetForm(row);
  form.create_timeStr = formatDate(row.create_time);
  isEditMode.value = true;
  dialogVisible.value = true;
};

// 重置表单
const resetForm = (data?: any) => {
  form.template_id = data?.template_id || 0;
  form.template_name = data?.template_name || "";
  form.creator_id = data?.creator_id || 0;
  form.content = data?.content || "";
  form.create_time = data?.create_time || Date.now();
};

// 提交表单（添加/更新）
const handleSubmit = async () => {
  if (!formRef.value) return;
  // 手动验证时间格式
  if (!form.create_timeStr) {
    return alert('请输入创建时间');
  }
  const isValid = await formRef.value.validate();
  if (!isValid) return;

  loading.value = true;
  try {
    const requestData = { 
      ...form, 
      create_time: form.create_time // 传递时间戳
    };
    
    if (isEditMode.value) {
      await axios.post("/template/update", requestData);
    } else {
      await axios.post("/template/add", requestData);
    }
    alert("操作成功");
    dialogVisible.value = false;
    fetchData();
  } catch (err: any) {
    alert(`操作失败：${err.response?.data?.message || "请检查输入或联系管理员"}`);
  } finally {
    loading.value = false;
  }
};

// 删除操作
const handleDelete = async (templateId: number) => {
  if (!window.confirm("确定要删除该模板吗？此操作不可恢复！")) return;
  
  try {
    await axios.post(
      "/template/delete",
      { templateId: templateId },
      { headers: { "Content-Type": "application/json" } }
    );
    alert("删除成功");
    fetchData();
  } catch (err: any) {
    alert(`删除失败：${err.response?.data?.message || "网络错误，请重试"}`);
  }
};

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false;
};

onMounted(fetchData);
</script>

<style scoped>
.template-management {
  padding: 24px;
  background-color: #f5f7fa;
}

.button-container {
  margin-bottom: 24px;
}

.table-container {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.custom-table {
  font-size: 16px;
}

.custom-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.custom-table :deep(.el-table__header .el-table__cell) {
  background-color: #f8f9fa;
  font-weight: bold;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}
</style>